using System;
using System.Collections;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using PHSRAG.Insight21.Common.Pages;
using PHSRAG.Insight21.Context;
using PHSRAG.Insight21.InsightWebControls;
using PHSRAG.Insight21.Policy;
using PHSRAG.Insight21.Purchasing;
using PHSRAG.Insight21.SearchContext;
using PHSRAG.Security.Enumerations;
using PHSRAG.Utility;
using PHSRAG.WebControls;
using Summary = PHSRAG.Insight21.Purchasing.UserOrderSummary;
using PurchasingConstants = PHSRAG.Insight21.Purchasing.Constants;
using Report = PHSRAG.Insight21.Purchasing.Reports;

namespace PHSRAG.Insight21
{

    #region Class UserOrderSummaryPage

    /// <summary>
    /// The UserOrderSummary class supports the UserOrderSummary.aspx page.
    /// It displays the summary view for all the personnel the currently loggedin user has access to.
    /// It also allows the user to drill down to the user order details page.
    /// </summary>
    /// <remarks>
    /// The UserOrderSummary page supports searching/filtering the UserOrderSummary data
    /// based on user-defined and user-selectable search criteria.
    /// Following is the list of such criteria:
    /// <list type="bullet">
    /// <item><description>PO Number (free-form entry)</description></item>
    /// <item><description>Vendor Name (free-form entry)</description></item>
    /// <item><description>Account Number (free-form entry)</description></item>
    /// <item><description>Fund Number (free-form entry)</description></item>
    /// <item><description>Invoice Number (free-form entry)</description></item>
    /// <item><description>Voucher Number (free-form entry)</description></item>
    /// <item><description>Journal Number (free-form entry)</description></item>
    /// <item><description>Requisition Number (free-form entry)</description></item>
    /// <item><description>Requestor name(free-form entry)</description></item>
    /// <item><description>Category (select from a drop-down list)</description></item>
    /// <item><description>PI (select from a DataGrid)</description></item>
    /// <item><description>Lab (select from a DataGrid)</description></item>
    /// <item><description>COS (select from a DataGrid)</description></item>
    /// </list>
    /// </remarks>
    public partial class UserOrderSummary : NoCachePage
    {
        #region Constants

        private const string CurrentPageIndexKey = "CurrentPageIndex_CF49BAE7-E396-47fb-8931-9A9BC26F3602";
        private const int DefaultDate = -90;
        private const int DefaultPageRank = 1;
        private const string DeleteCheckBoxes = "DeleteThis";
        private const string DeleteFlagKey = "DeleteFlag_CF49BAE7-E396-47fb-8931-9A9BC26F3602";
        private const string DeletePopupJSKey = "DeletePopupJS_CF49BAE7-E396-47fb-8931-9A9BC26F3602";
        private const string SearchCriteriaVersionKey = "SearchCriteriaVersion_CF49BAE7-E396-47fb-8931-9A9BC26F3602";
        private const string TransactionDateFromKey = "TransactionDateFrom_CF49BAE7-E396-47fb-8931-9A9BC26F3602";
        private const string TransactionDateToKey = "TransactionDateTo_CF49BAE7-E396-47fb-8931-9A9BC26F3602";

        #endregion

        #region Enumerations (Private)

        /// <summary>
        /// The DataGridColumns enumeration defines values 
        /// for indexing columns in the datagrid.
        /// </summary>
        private enum DataGridColumnsIndex
        {
            OrderType,
            OrderID,
            OrderNumber,
            RequisitionNumber,
            InvoiceNumber,
            Requestor,
            Vendor,
            TransactionDate,
            FundNumber,
            TotalAmount
        }

        #endregion

        #region Instance variables (Private)

        private ICachePolicy cachePolicy;
        private ICachePolicy pageCachePolicy;
        private ViewStateCachePolicy viewStateCachePolicy;

        #endregion

        #region Instance variables (Protected)

        private UserOrderSummaries userOrderSummaries;

        #endregion

        #region Private Properties

        /// <summary>
        /// Get/Set the current page index in pagecache policy, 
        /// datagrid use this to set the Current page index for display. 
        /// This information persists across page loads.
        /// </summary>
        private int CurrentPageIndex
        {
            get
            {
                Hashtable h = pageCachePolicy.GetCachedObject(Keys.UserOrderSummaryPageKey) as Hashtable;
                return (h == null || h[CurrentPageIndexKey] == null) ? 0 : (int) h[CurrentPageIndexKey];
            }
            set
            {
                Hashtable h = pageCachePolicy.GetCachedObject(Keys.UserOrderSummaryPageKey) as Hashtable ?? new Hashtable();
                h[CurrentPageIndexKey] = value;
                dataGrid.CurrentPageIndex = value;
                pageCachePolicy.Cache(Keys.UserOrderSummaryPageKey, h);
            }
        }

        /// <summary>
        /// Get the User Order Summaries informations that the logged-in user has access to. The list of User Orders data is
        /// is maintained by the UserOrderSummaries business object within its data container. This object is cached.
        /// </summary>
        private UserOrderSummaries UserOrderSummariesInstance
        {
            get
            {
                CommonSearchContext searchContext =
                    (CommonSearchContext) cachePolicy.GetCachedObject(CommonSearchContext.CacheKey);
                SearchCriteria searchCriteria = searchContext.GetSearchCriteria(Page.Request.Url.ToString());
                int searchVersion = searchCriteria.Version;

                UserOrderSummaries userOrderSummaries =
                    cachePolicy.GetCachedObject(UserOrderSummaries.CacheKey) as UserOrderSummaries;
                if (userOrderSummaries == null || searchVersion != SearchCriteriaVersion)
                {
                    SearchCriteriaVersion = searchVersion;
                    userOrderSummaries = new UserOrderSummaries(cachePolicy);
                    userOrderSummaries.Load(DataAccess.ConnectionString,
                        ((CommonSearchContext) cachePolicy.GetCachedObject(CommonSearchContext.CacheKey)).GetSearchCriteria(Page.Request.Url.ToString()));
                    userOrderSummaries.Cache();
                }
                return userOrderSummaries;
            }
        }

        /// <summary>
        /// Gets/sets an integer value indicating the search criteria version. 
        /// The version number changes when the search criteria changes.  This signals the page to re-build its
        /// cache.
        /// </summary>
        /// <remarks>
        /// This and all properties required to re-establish the page are stored as name / value pairs in
        /// a hash table stored in the page cache under the key Keys.FinancialSummaryPageKey.
        /// This enables the page to re-establish its state with minimal IO to what it was when
        /// the user last visited it.
        /// </remarks>
        private int SearchCriteriaVersion
        {
            get
            {
                Hashtable h = pageCachePolicy.GetCachedObject(Keys.UserOrderSummaryPageKey) as Hashtable;
                return (h == null || h[SearchCriteriaVersionKey] == null) ? 0 : (int) h[SearchCriteriaVersionKey];
            }

            set
            {
                Hashtable h = pageCachePolicy.GetCachedObject(Keys.UserOrderSummaryPageKey) as Hashtable;
                if (h == null)
                {
                    h = new Hashtable();
                }
                h[SearchCriteriaVersionKey] = value;
                pageCachePolicy.Cache(Keys.UserOrderSummaryPageKey, h);
            }
        }

        #endregion

        #region Event Handlers

        #region Page load

        /// <summary>
        /// Handler for the event raised when the page is being loaded.
        /// Set the transaction dates to the last 90 days range for default load
        /// Initialize the bread crumb control, set the page size for the data grid, and load the data grid with data.
        /// Set the visibility of the Add and Delete buttons depending on the users module bit mask
        /// If on the first page within the data grid, initalize the pager control.
        /// </summary>
        /// <param name="sender">Control which raised the event</param>
        /// <param name="e">Argument associated with the event</param>
        protected void OnPageLoad(object sender, EventArgs e)
        {
            reportDownload.SQLReportName = "userordersummary";

            annunciator.Message = string.Empty;
            annunciator.Title = string.Empty;

            breadCrumb.Add(Constants.UserOrderSummary, Settings.
                GetKeyValue("SubNavigation.Purchasing.UserOrderSummaryURL", string.Empty), DefaultPageRank);

            if (!IsPostBack)
            {
                dataGrid.PageSize = Settings.GetKeyValue("DataGrid.ItemsPerPage", 10);
                SetTransactionDates();
                LoadDataGrid();

                ((ExpansionToggler) expandingPanel.FindControl("expansionToggler")).HelpText =
                    InsightUtilities.Constants.SearchHelpText;

                UserContext userContext = cachePolicy.GetCachedObject(UserContext.CacheKey) as UserContext;

                if ((userContext.ModuleRoleBitmask & (int) ModuleRoleBit.ManageUserOrders) == 0)
                {
                    addUserOrder.Visible = deleteUserOrders.Visible = false;
                }

                expandingPanel.IsExpanded = true;
            }
            else
            {
                // need to clear additional search criteria that would have been added
                // by calling SetTransactionDate() method so that they do not stick aroud
                // even after clicking "search".
                ((CommonSearchContext) cachePolicy.GetCachedObject(CommonSearchContext.CacheKey)).ClearAdditionalSearchCriteria(Page.Request.Url.ToString());
            }

            //If anything has been deleted in the delete user orders popup, reload the data
            object flag = viewStateCachePolicy.GetCachedObject(DeleteFlagKey);
            bool reloadFlag = (flag == null) ? false : (bool) flag;
            if (reloadFlag)
            {
                LoadDataGrid();
                viewStateCachePolicy.Cache(DeleteFlagKey, false);
            }
            if (CurrentPageIndex == 0)
            {
                InitializePager();
            }
            else
            {
                ManageNavigationLinks();
            }
            ManagePagination();

            purchasingSubNavigation.SelectedSummaryLink = PurchasingSubNavigation.UserOrderSummaryCommand;
        }

        #endregion

        #region Datagrid event handlers

        /// <summary>
        /// Handler for event raised while each data grid item is created.
        /// Help in putting the symbol denoting the sort column in the data grid.
        /// If the item being created is the data grid header:
        /// <list type="bullet">
        /// <item><description>Get the sort column and sort order from the UserOrderSummaries instance in the cache</description></item>
        /// <item><description>Create a Hashtable of column indices, keyed by the sort expression of each column</description></item>
        /// <item><description>Using the hash table add a label with sort symbol to the column on which sort has happened</description></item>
        /// </list>
        /// </summary>
        /// <param name="sender">Control which raised the event</param>
        /// <param name="e">Argument associated with the event</param>
        protected void OnItemCreated(object sender, DataGridItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Header)
            {
                userOrderSummaries = UserOrderSummariesInstance;

                Label sortSymbol = new Label();

                sortSymbol.Text = userOrderSummaries.SortAscending ? InsightUtilities.Constants.SortAscendingText : InsightUtilities.Constants.SortDescendingText;
                sortSymbol.Font.Name = InsightUtilities.Constants.SortSymbolFontName;

                Hashtable columnMap = new Hashtable();
                foreach (DataGridColumn column in dataGrid.Columns)
                {
                    columnMap[column.SortExpression] = dataGrid.Columns.IndexOf(column);
                }

                string sortColumn = userOrderSummaries.SortColumn;
                if (columnMap.ContainsKey(sortColumn))
                {
                    (e.Item.Cells[(int) columnMap[sortColumn]]).Controls.Add(sortSymbol);
                }
            }
            if (e.Item.ItemType == ListItemType.Header || e.Item.ItemType == ListItemType.Item)
            {
                ((CheckBox) (e.Item.Cells[10]).Controls[1]).Attributes["onclick"] = "javascript: return select_deselectAll (this.checked, this.id);";
            }
        }

        /// <summary>
        /// Handler for the event raised when a row in the datagrid is clicked upon.
        /// If the "OrderId" was clicked upon (its CommandName is "LinkToDetails"), load the UserOrderDetails page
        /// </summary>
        /// <param name="source">Control which raised the event</param>
        /// <param name="e">Argument associated with the event</param>
        protected void OnItemCommand(object source, DataGridCommandEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                if (e.CommandName == Constants.CommandName)
                {
                    Hashtable dictionary = new Hashtable();
                    dictionary.Add(Keys.UserOrderIdKey
                        , Convert.ToInt32(e.Item.Cells[(int) DataGridColumnsIndex.OrderID].Text.Trim()));
                    pageCachePolicy.Cache(Keys.IncomingDataKey, dictionary);

                    PurgeCache();
                    Response.Redirect
                        (Settings.GetKeyValue("SubNavigation.PurchasingDetails.UserOrderDetailsURL", string.Empty));
                }
            }
        }

        /// <summary>
        /// Handler for the event raised when a column header within the data grid is clicked.
        /// Set the currentpageindex to 0 as sorting need to be done on all records and not only on what is visible
        /// Load the data grid and intialize the pager controls
        /// </summary>
        /// <param name="sender">Control which raised the event</param>
        /// <param name="e">Argument associated with the event</param>
        private void OnSort(object sender, DataGridSortCommandEventArgs e)
        {
            if (e.SortExpression != string.Empty)
            {
                UserOrderSummaries userOrders = UserOrderSummariesInstance;
                userOrders.Sort(e.SortExpression);
                userOrders.Cache();
                CurrentPageIndex = 0;
                LoadDataGrid();
                InitializePager();
            }
        }

        /// <summary>
        /// Handler for event raised when an item is data bound to MatchedOrdersDataGrid.
        /// While binding data check if the amount field has negative values then assign a 
        /// style for displaying negative values. This formatting  is applied only to Item 
        /// types and alternating Item types.
        /// </summary>
        /// <param name="sender">Control which raised the event</param>
        /// <param name="e">Argument associated with the event</param>
        private void OnItemDataBound(object sender, DataGridItemEventArgs e)
        {
            try
            {
                if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
                {
                    TableCell amount = e.Item.Cells[(int) DataGridColumnsIndex.TotalAmount];
                    decimal orderAmount = ((Summary) e.Item.DataItem).TotalAmount;
                    if (orderAmount < 0)
                    {
                        amount.CssClass = Constants.DeficitStyle;
                    }
                    amount.Text = orderAmount.ToString("c");
                }
            }
            catch (Exception ex)
            {
                annunciator.Message = String.Format("{0} Error while attempting to format amount.",
                    ExceptionReport.GetExceptionInfo(ex, false));
            }
        }

        #endregion

        #region Paging event handlers

        /// <summary>
        /// Handler for the event raised when the FirstPage link in clicked in the Pager control.
        /// Set the current page index to 0, bind the datagrid with data and manage navigation links. To avoid superfluous
        /// data binding activites, no action is taken if the current page index is already 0.
        /// </summary>
        /// <param name="sender">Control which rasied the event</param>
        /// <param name="e">Arguments associated with the event</param>
        protected void OnFirstPage(object sender, CommandEventArgs e)
        {
            CurrentPageIndex = 0;
            ManagePagination();
            LoadDataGrid();
            ManageNavigationLinks();
        }

        /// <summary>
        /// Handler for the event raised when the LastPage link in clicked in the Pager control.
        /// Set the current page index to one less than the total page count (index is 0-based), bind the datagrid with
        /// data and manage navigation links. To avoid superfluous data binding activites, no action is taken if the current
        /// page index is already corresponding to the last page.
        /// </summary>
        /// <param name="sender">Control which rasied the event</param>
        /// <param name="e">Arguments associated with the event</param>
        protected void OnLastPage(object sender, CommandEventArgs e)
        {
            CurrentPageIndex = pagerAboveDatagrid.PageCount - 1;
            ManagePagination();
            LoadDataGrid();
            ManageNavigationLinks();
        }

        /// <summary>
        /// Handler for the event raised when the NextPage link in clicked in the Pager control.
        /// Increment the current page index, bind the datagrid with data and manage navigation links.
        /// </summary>
        /// <param name="sender">Control which rasied the event</param>
        /// <param name="e">Arguments associated with the event</param>
        protected void OnNextPage(object sender, CommandEventArgs e)
        {
            ++CurrentPageIndex;
            ManagePagination();
            LoadDataGrid();
            ManageNavigationLinks();
        }

        /// <summary>
        /// Handler for the event raised when the PreviousPage link in clicked in the Pager control.
        /// Decrement the current page index, bind the datagrid with data and manage navigation links.
        /// </summary>
        /// <param name="sender">Control which rasied the event</param>
        /// <param name="e">Arguments associated with the event</param>
        protected void OnPreviousPage(object sender, CommandEventArgs e)
        {
            --CurrentPageIndex;
            ManagePagination();
            LoadDataGrid();
            ManageNavigationLinks();
        }

        #endregion

        #region Search event handler

        /// <summary>
        /// Handler for the event raised by the CommonSearch control when the "Clear Selection" buttion is clicked upon.
        /// The control reset the transaction date range to 90 days and clears the criretria (specific to this module).
        /// </summary>
        /// <param name="sender">Sender of the event</param>
        /// <param name="e">Argument associated with the event</param>
        protected void OnClearSelection(object sender, CommandEventArgs e)
        {
            try
            {
                dataGrid.Visible = pagerBelowDatagrid.Visible = pagerAboveDatagrid.Visible = false;
            }
            catch (Exception ex)
            {
                annunciator.Message = String.Format("{0} Error while attempting to search for user orders.",
                    ExceptionReport.GetExceptionInfo(ex, false));

                dataGrid.Visible = pagerBelowDatagrid.Visible = pagerAboveDatagrid.Visible = false;
            }
        }

        /// <summary>
        /// Handler for the event raised when the Search button is clicked in the Search control.
        /// Gets the search criteia and performs a search. The actual search is performed by the UserOrderSummaries object
        /// which returns true if it did indeed apply any filteration criteria, and false otherwise. This predicate
        /// is used by LoadDataGrid() to control the visibility of the pager controls.
        /// </summary>
        /// <param name="args">Search Criteria args associated with the search event</param>
        protected void OnSearch(SearchCriteriaArgs args)
        {
            try
            {
                if (SearchCriteriaVersion == -1)
                {
                    ++SearchCriteriaVersion;
                }
                CurrentPageIndex = 0;
                LoadDataGrid();
            }
            catch (Exception ex)
            {
                annunciator.Message = String.Format("{0} Error while attempting to search for user orders.",
                    ExceptionReport.GetExceptionInfo(ex, false));

                dataGrid.Visible = pagerBelowDatagrid.Visible =
                    pagerAboveDatagrid.Visible = false;
            }
        }

        #endregion

        #region Button click event handlers

        /// <summary>
        /// Event handler for Deleting user order button, OnDeleteUserOrders creates a comma seperated
        /// stringbuilder list by looping through the DataGridItems and checking which items have DeleteCheckBox checked
        /// This stringbuilder with UserOrder Ids is passed to UserOrderUtility.DeleteUserOrders method,
        /// DeleteUserOrders method deletes these user orders from user Order and Reconcile Tables.
        /// after users orders are deleted event handler clears the old cache and reloads the data grid.
        /// </summary>
        /// <param name="sender">Control which raised the event</param>
        /// <param name="e">Argument associated with the event</param>
        protected void OnDeleteUserOrders(object sender, ImageClickEventArgs e)
        {
            try
            {
                StringBuilder orderIDList = new StringBuilder();
                foreach (DataGridItem item in dataGrid.Items)
                {
                    if (((CheckBox) item.FindControl(DeleteCheckBoxes)).Checked)
                    {
                        orderIDList.Append(String.Concat(item.Cells[(int) DataGridColumnsIndex.OrderID].Text, ","));
                    }
                }
                if (orderIDList.Length > 0)
                {
                    Hashtable dictionary = new Hashtable();
                    dictionary.Add(Keys.UserOrderIDListKey, orderIDList);
                    pageCachePolicy.Cache(Keys.IncomingDataKey, dictionary);
                    viewStateCachePolicy.Cache(DeleteFlagKey, true);
                }
                ClientScript.RegisterStartupScript
                    (GetType(), DeletePopupJSKey
                        , "<script>window.open('DeleteUserOrder.aspx',null,'width=700,height=500,scrollbars=yes,resizable=no,status=no');</script>");
            }
            catch (Exception ex)
            {
                annunciator.Message = ExceptionReport.GetExceptionInfo(ex, false);
            }
        }

        /// <summary>
        /// Event handler for Adding new user orders, 
        /// Redirects to UserOrderSummary page for creating new User Orders
        /// </summary>
        /// <param name="sender">Control which raised the event</param>
        /// <param name="e">Argument associated with the event</param>
        private void OnAddUserOrder(object sender, ImageClickEventArgs e)
        {
            Response.Redirect
                (Settings.GetKeyValue("SubNavigation.PurchasingDetails.UserOrderDetailsURL", string.Empty));
        }

        #endregion

        #region Download bar event handlers

        /// <summary>
        /// Invoked by the download bar when it catches an exception.
        /// </summary>
        /// <param name="sender">Control which raised the event</param>
        /// <param name="e">Argument associated with the event</param>
        protected void OnDownloadFailed(object sender, CommandEventArgs e)
        {
            annunciator.Title = "Following error(s) occurred while downloading";
            annunciator.Message = ExceptionReport.GetExceptionInfo((Exception) e.CommandArgument, false);
        }

        #endregion

        #region Criteria Display Handlers

        /// <summary>
        /// Fires when the criteria display tries to display the search criteria on the page.
        /// </summary>
        /// <param name="criteriaKey">The criteria key.</param>
        /// <returns>Whether or not to display.</returns>
        private bool OnDisplayCriteria(string criteriaKey)
        {
            string criteriaKeyLowerCase = criteriaKey.ToLower();
            return criteriaKeyLowerCase == InsightUtilities.Constants.PIIDKey ||
                criteriaKeyLowerCase == InsightUtilities.Constants.CosKey ||
                    criteriaKeyLowerCase == InsightUtilities.Constants.PurchasingSearchKey.PONumberKey ||
                        criteriaKeyLowerCase == InsightUtilities.Constants.PurchasingSearchKey.VendorNameKey ||
                            criteriaKeyLowerCase == InsightUtilities.Constants.PurchasingSearchKey.AccountNumberKey ||
                                criteriaKeyLowerCase == InsightUtilities.Constants.PurchasingSearchKey.InvoiceNumberKey ||
                                    criteriaKeyLowerCase == InsightUtilities.Constants.PurchasingSearchKey.RequestorNameKey ||
                                        criteriaKeyLowerCase == InsightUtilities.Constants.PurchasingSearchKey.CategoryIdKey ||
                                            criteriaKeyLowerCase == InsightUtilities.Constants.PurchasingSearchKey.VoucherNumberKey ||
                                                criteriaKeyLowerCase == InsightUtilities.Constants.PurchasingSearchKey.RequisitionNumberKey ||
                                                    criteriaKeyLowerCase == InsightUtilities.Constants.PurchasingSearchKey.TransactionDateFromKey ||
                                                        criteriaKeyLowerCase == InsightUtilities.Constants.PurchasingSearchKey.TransactionDateToKey ||
                                                            criteriaKeyLowerCase == InsightUtilities.Constants.FundIDKey ||
                                                                criteriaKeyLowerCase == InsightUtilities.Constants.PurchasingSearchKey.UserOrderTypeViewKey ? true : false;
        }

        #endregion

        #region Header

        /// <summary>
        /// Resets the subnavigation selected link(s) before the 
        /// header performs a redirect.
        /// </summary>
        /// <param name="sender">Control which rasied the event.</param>
        /// <param name="e">Arguments associated with the event.</param>
        private void OnHeaderNavigate(object sender, CommandEventArgs e)
        {
            purchasingSubNavigation.Reset();

            PurgeCache();
        }

        #endregion

        #endregion

        #region	Private Methods

        /// <summary>
        /// Load the datagrid with sufficient data for display within one page of the data grid. This is done as follows:
        /// Get the summaries for all user orders that the user has access to. Use that to initialize the data grid and
        /// the pager controls based on the page size of the data grid.
        /// The pagers are made visible only when more than one page of data can be displayed.
        /// If there is no data to display, warn the user via the annunciator.
        /// </summary>
        private void LoadDataGrid()
        {
            try
            {
                userOrderSummaries = UserOrderSummariesInstance;

                dataGrid.VirtualItemCount = pagerBelowDatagrid.RecordCount =
                    pagerAboveDatagrid.RecordCount = userOrderSummaries.Count;

                int currentPageIndex = CurrentPageIndex;

                int pageCount = (pagerAboveDatagrid.RecordCount/dataGrid.PageSize) +
                    (((pagerAboveDatagrid.RecordCount%dataGrid.PageSize) == 0) ? 0 : 1);

                pagerBelowDatagrid.PageCount = pagerAboveDatagrid.PageCount = pageCount;
                pagerBelowDatagrid.CurrentPage = pagerAboveDatagrid.CurrentPage = currentPageIndex + 1;
                //CommonSearchContext searchContext =
                //  (CommonSearchContext)cachePolicy.GetCachedObject(CommonSearchContext.CacheKey);
                //SearchCriteria searchCriteria = searchContext.GetSearchCriteria(Page.Request.Url.ToString());
                //if (searchCriteria["userordertypeview"] != null)
                //{
                //    string orderType = searchCriteria["userordertypeview"].ToString();
                //    switch (orderType)
                //    {
                //        case "1":
                //            dataGrid.Columns[3].Visible = true;
                //            dataGrid.Columns[4].Visible = true;
                //            dataGrid.Columns[6].Visible = true;
                //            break;
                //        case "2":
                //            dataGrid.Columns[4].Visible = true;
                //            dataGrid.Columns[6].Visible = true;
                //            dataGrid.Columns[3].Visible = false;
                //            break;
                //        case "3":
                //            dataGrid.Columns[4].Visible = true;
                //            dataGrid.Columns[6].Visible = true;
                //            dataGrid.Columns[3].Visible = false;
                //            break;
                //        case "4":
                //            dataGrid.Columns[3].Visible = false;
                //            dataGrid.Columns[4].Visible = false;
                //            dataGrid.Columns[6].Visible = false;
                //            break;
                //        case "5":
                //            dataGrid.Columns[3].Visible = false;
                //            dataGrid.Columns[4].Visible = false;
                //            dataGrid.Columns[6].Visible = false;
                //            break;

                //        default:
                //            break;
                //    }
                //}
                dataGrid.DataSource = userOrderSummaries.GetUserOrderSummaryList
                    (currentPageIndex*dataGrid.PageSize, dataGrid.PageSize);
                dataGrid.DataBind();

                if (dataGrid.Items.Count == 0)
                {
                    dataGrid.Visible = pagerBelowDatagrid.Visible =
                        pagerAboveDatagrid.Visible = deleteUserOrders.Visible = false;
                    annunciator.Message = "No user order summary data found for user";
                }
                else
                {
                    dataGrid.Visible = pagerBelowDatagrid.Visible =
                        pagerAboveDatagrid.Visible = true;
                    ManagePagination();
                    ManageNavigationLinks();
                }
            }
            catch (Exception ex)
            {
                annunciator.Message = ExceptionReport.GetExceptionInfo(ex, false);
            }
        }

        /// <summary>
        /// ManageNavigationLinks determines which links should be active and which should be inactive
        /// for the first page and last page links.
        /// </summary>
        private void ManageNavigationLinks()
        {
            pagerBelowDatagrid.EnableFirstPage = pagerAboveDatagrid.EnableFirstPage =
                pagerBelowDatagrid.EnablePreviousPage = pagerAboveDatagrid.EnablePreviousPage =
                    (CurrentPageIndex != 0);

            pagerBelowDatagrid.EnableLastPage = pagerAboveDatagrid.EnableLastPage =
                pagerBelowDatagrid.EnableNextPage = pagerAboveDatagrid.EnableNextPage =
                    (CurrentPageIndex != (pagerAboveDatagrid.PageCount - 1));
        }

        /// <summary>
        /// Initialize the first record, last record and current page values for the pager controls
        /// This will be called only when a pager needs to be intialized, 
        /// so set the first record and the current page values to 1 and the last page value to the grid page size 
        /// Set the current page index to 0 and manage the navigation links.
        /// </summary>
        private void InitializePager()
        {
            pagerBelowDatagrid.FirstRecord = pagerAboveDatagrid.FirstRecord = 1;
            pagerBelowDatagrid.CurrentPage = pagerAboveDatagrid.CurrentPage = 1;
            CurrentPageIndex = 0;
            ManageNavigationLinks();
        }

        /// <summary>
        /// Manages the pagination logic.
        /// Set the First record and last record values for the pager controls
        /// based on the current page index and the data grid page size respectively
        /// </summary>
        private void ManagePagination()
        {
            int currentPageIndex = CurrentPageIndex;
            dataGrid.CurrentPageIndex = currentPageIndex;

            int startIndex = currentPageIndex*dataGrid.PageSize;

            pagerBelowDatagrid.FirstRecord = pagerAboveDatagrid.FirstRecord = startIndex + 1;
            pagerBelowDatagrid.LastRecord = pagerAboveDatagrid.LastRecord =
                Math.Min(startIndex + dataGrid.PageSize, UserOrderSummariesInstance.Count);
        }

        /// <summary>
        /// Register Client Script is used to register Java Script that lets user click on 
        /// DataGrid Delete column to select all user orders for delete
        /// </summary>
        private void RegisterClientScripts()
        {
            //Implement Client Side JavaScript code
            string script = "<script language=JavaScript> \n" +
                "<!--\n" +
                "function select_deselectAll (chkVal, idVal) {\n" +
                "var frm = document.forms[0];\n" +
                "// loop through all elements\n" +
                " for (i=0; i<frm.length; i++) {\n" +
                " // // Look for our Header Template's Checkbox\n" +
                " if (idVal.indexOf ('CheckAll') != -1) {\n" +
                " // Check if main checkbox is checked, then select or deselect datagrid checkboxes \n" +
                " if(chkVal == true) {\n" +
                " frm.elements[i].checked = true;\n" +
                " } else {\n" +
                " frm.elements[i].checked = false;\n" +
                " }\n" +
                " // Work here with the Item Template's multiple checkboxes\n" +
                " } else if (idVal.indexOf('DeleteThis') != -1) {\n" +
                " // Check if any of the checkboxes are not checked, and then uncheck top select all checkbox\n" +
                " if(frm.elements[i].checked == false) {\n" +
                " frm.elements[1].checked = false; // Check if any of the checkboxes are not checked, and then uncheck top select all checkbox\n" +
                " }\n" +
                " }\n" +
                " }\n" +
                "}" +
                "//--> \n" +
                "</script>";

            //Allows our .NET page to add client-side script blocks when page loads, instead of the conventional HTML JS tags.
            ClientScript.RegisterClientScriptBlock(GetType(), "clientScript", script);
        }

        /// <summary>
        /// Set the Transaction from and to dates depending on the state of the search criteria
        /// If the searchCriteria contains these dates set the local private properties to the value in the Search Criteria
        /// if otherwise set them to the default values
        /// </summary>
        private void SetTransactionDates()
        {
            CommonSearchContext searchContext =
                cachePolicy.GetCachedObject(CommonSearchContext.CacheKey) as CommonSearchContext;

            if (searchContext != null)
            {
                SearchCriteria searchCriteria = searchContext.GetSearchCriteria(Page.Request.Url.ToString());
                if (searchCriteria[InsightUtilities.Constants.PurchasingSearchKey.TransactionDateFromKey] == null)
                {
                    searchContext.SetPrimarySearchCriteria(SearchCriteria.Level.Summary,
                        Page.Request.Url.ToString(),
                        InsightUtilities.Constants.PurchasingSearchKey.TransactionDateFromKey,
                        DateTime.Now.AddDays(Settings.GetKeyValue
                            ("Purchasing.DefaultFromDate", DefaultDate)).ToShortDateString(), PurchasingSearch.TransactionDateFromLabel, CommonSearch.LabelValueSeparator,
                        DateTime.Now.AddDays(Settings.GetKeyValue
                            ("Purchasing.DefaultFromDate", DefaultDate)).ToShortDateString());
                }

                if (searchCriteria[InsightUtilities.Constants.PurchasingSearchKey.TransactionDateToKey] == null)
                {
                    searchContext.SetPrimarySearchCriteria(SearchCriteria.Level.Summary,
                        Page.Request.Url.ToString(),
                        InsightUtilities.Constants.PurchasingSearchKey.TransactionDateToKey,
                        DateTime.Now.ToShortDateString(), PurchasingSearch.TransactionDateToLabel, CommonSearch.LabelValueSeparator, DateTime.Now.ToShortDateString());
                }
            }
        }

        #endregion

        #region Overrides OnPreRender

        /// <summary>
        /// Register clientside scripts.
        /// </summary>
        /// <param name="e">Argument associated with the event.</param>
        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            RegisterClientScripts();
        }

        #endregion

        #region Web Form Designer generated code

        /// <summary>
        /// Handler for the event raised when the page is being initialized.
        /// Retrieve the cache policy and page cache policy in force.
        /// Deposit event handlers to support the datagrid pagination.
        /// </summary>
        /// <param name="e">Argument associated with the event</param>
        protected override void OnInit(EventArgs e)
        {
            InitializeComponent();
            base.OnInit(e);
            cachePolicy = (Policy.ICachePolicy) Session[Policy.Names.CachePolicyKey];
            viewStateCachePolicy = new PHSRAG.Insight21.Policy.ViewStateCachePolicy(this.ViewState);
            pageCachePolicy = (Policy.ICachePolicy) Session[Policy.Names.PageCachePolicyKey];

            pagerAboveDatagrid.NextPage += new CommandEventHandler(OnNextPage);
            pagerAboveDatagrid.PreviousPage += new CommandEventHandler(OnPreviousPage);
            pagerAboveDatagrid.FirstPage += new CommandEventHandler(OnFirstPage);
            pagerAboveDatagrid.LastPage += new CommandEventHandler(OnLastPage);

            pagerBelowDatagrid.NextPage += new CommandEventHandler(OnNextPage);
            pagerBelowDatagrid.PreviousPage += new CommandEventHandler(OnPreviousPage);
            pagerBelowDatagrid.FirstPage += new CommandEventHandler(OnFirstPage);
            pagerBelowDatagrid.LastPage += new CommandEventHandler(OnLastPage);

            this.reportDownload.FailedAction += new CommandEventHandler(OnDownloadFailed);
        }

        /// <summary>
        /// Required method for Designer support 
        /// </summary>
        private void InitializeComponent()
        {
            this.insightHeader.Navigate += new System.Web.UI.WebControls.CommandEventHandler(this.OnHeaderNavigate);
            this.purchasingSubNavigation.Navigate += new System.Web.UI.WebControls.CommandEventHandler(this.OnSubHeaderNavigate);
            this.searchCriteriaDisplay.DisplayCriteria += new PHSRAG.Insight21.InsightWebControls.SearchCriteriaDisplay.CriteriaDisplayEventHandler(this.OnDisplayCriteria);
            this.breadCrumb.Navigate += new System.Web.UI.WebControls.CommandEventHandler(this.OnBreadCrumbNavigate);
            this.dataGrid.ItemCreated += new System.Web.UI.WebControls.DataGridItemEventHandler(this.OnItemCreated);
            this.dataGrid.ItemCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.OnItemCommand);
            this.dataGrid.SortCommand += new System.Web.UI.WebControls.DataGridSortCommandEventHandler(this.OnSort);
            this.dataGrid.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(this.OnItemDataBound);
            this.addUserOrder.Click += new ImageClickEventHandler(OnAddUserOrder);
            this.deleteUserOrders.Click += new ImageClickEventHandler(OnDeleteUserOrders);
            this.Load += new System.EventHandler(this.OnPageLoad);
        }

        #endregion

        private void OnSubHeaderNavigate(object sender, CommandEventArgs e)
        {
            PurgeCache();
        }

        private void OnBreadCrumbNavigate(object sender, CommandEventArgs e)
        {
            PurgeCache();
        }

        public void PurgeCache()
        {
            if (userOrderSummaries != null)
            {
                userOrderSummaries.Purge();
            }

            cachePolicy.UnCache(UserOrderSummaries.CacheKey);
        }
    }

    #endregion
}